# 重命名
# -*- coding: utf-8 -*-
# @Time    : 2023-12-14 15:58
# @Author  : Jiang Liu

import os
import shutil

from tqdm import tqdm


def batch_rename_images_and_annotations(img_dir, txt_dir, renamed_img_dir, renamed_txt_dir, ext_img='.jpg',
                                        ext_ann='.txt'):
    # 获取所有图片文件
    img_filenames = [f for f in os.listdir(img_dir) if f.endswith(ext_img)]
    img_filenames.sort()  # 可以根据需要选择是否排序

    for idx, img_filename in tqdm(enumerate(img_filenames)):
        old_basename = os.path.splitext(img_filename)[0]
        # 构建新的文件名
        new_img_name = "{:08d}".format(idx) + ext_img
        new_ann_name = "{:08d}".format(idx) + ext_ann

        # 获取原始的标注文件名
        ann_filename = old_basename + ext_ann

        # 构建完整的文件路径
        old_img_path = os.path.join(img_dir, img_filename)
        old_ann_path = os.path.join(txt_dir, ann_filename)
        new_img_path = os.path.join(renamed_img_dir, new_img_name)
        new_ann_path = os.path.join(renamed_txt_dir, new_ann_name)

        # 将图片和标注文件按新的文件名保存到新的文件夹中
        shutil.copy(old_img_path, new_img_path)
        shutil.copy(old_ann_path, new_ann_path)


def main():
    img_dir = 'JPEGImages/'
    txt_dir = 'labelsLJ/'
    renamed_img_dir = './processed/images/'
    renamed_txt_dir = './processed/labels/'
    os.mkdir('processed')
    os.mkdir('processed/images')
    os.mkdir('processed/labels')
    batch_rename_images_and_annotations(img_dir, txt_dir, renamed_img_dir, renamed_txt_dir)


if __name__ == '__main__':
    main()
